﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace OpenRPOSBackOffice
{
    public partial class AddMenuCategoryDialog : ChildWindow
    {

        public AddMenuCategoryDialog()
        {
            InitializeComponent();
        }

        private async void btnOK_Click(object sender, RoutedEventArgs e)
        {
            // Get the top precedence number 
            short maxPrecedence=0;
            foreach (ServiceReferenceOpenRPOS.MenuCategory mc in Globals.db.MenuCategoryRecords)
            {
                if (mc.col_Precedence > maxPrecedence)
                    maxPrecedence = mc.col_Precedence;
            }
            // Determine if a non-active record with this name already exists
            await Globals.db.GetMenuCategoryObjects("Active=0 and Name='" + tbMenuCategoryName.Text.Trim() + "'");
            if (Globals.db.MenuCategoryRecords.Count > 0)
            {
                Globals.db.MenuCategoryRecords[0].col_Active = true;
                Globals.db.MenuCategoryRecords[0].bFilterActive = true;
                Globals.db.MenuCategoryRecords[0].col_Name = tbMenuCategoryName.Text.Trim();
                Globals.db.MenuCategoryRecords[0].bFilterName = true;
                await Globals.db.UpdateMenuCategoryObject(Globals.db.MenuCategoryRecords[0]);
            }
            else
            {
                // Create a new menu category with this name
                ServiceReferenceOpenRPOS.MenuCategory mc = new ServiceReferenceOpenRPOS.MenuCategory();
                mc.col_Name = tbMenuCategoryName.Text.Trim();
                mc.bFilterName = true;
                mc.col_Active = true;
                mc.bFilterActive = true;
                mc.col_Precedence = (short)(maxPrecedence + 1);
                mc.bFilterPrecedence = true;
                await Globals.db.AddMenuCategoryObject(mc);
            }
            // Re-init the display
            Globals.menuItems.initMenuCategories(true);
            Globals.menuItems.initMenuItems(true);
            this.DialogResult = true;
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }

        private void tbMenuCategoryName_KeyDown(object sender, KeyEventArgs e)
        {
            // Call the OK button handlers if "Enter" is pressed
            if (e.Key == Key.Enter)
                btnOK_Click(sender, e);
        }

    }
}

